package com.artogrid.framework.commons.jedis;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.artogrid.framework.commons.utils.Props;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * 连接和使用redis资源的工具类
 * 
 * @author yinshuwei
 */
public class JedisFactory {
	private JedisFactory() {
	}

	private static Logger log = LoggerFactory.getLogger(JedisFactory.class);

	/**
	 * 数据源
	 */
	private static JedisPool jedisPool;
	private static boolean inited = false;

	/**
	 * 获取数据库连接
	 * 
	 * @return conn
	 */
	public static Jedis createJedis() {
		Jedis jedis = null;
		try {
			if (!inited) {
				initJedisConfig();
			}
			jedis = jedisPool.getResource();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jedis;
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @param conn
	 */
	public static void closeJedis(Jedis jedis) {
		if (null != jedis) {
			try {
				jedisPool.returnResource(jedis);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 初始化Jedis
	 * 
	 * @param ip
	 * @param port
	 * @param maxActive
	 * @param maxIdle
	 * @param maxWait
	 * @param testOnBorrow
	 */
	public static void initJedisConfig(String ip, int port, int maxActive, int maxIdle, long maxWait, boolean testOnBorrow, int timeout) {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.maxActive = maxActive;
		jedisPoolConfig.maxIdle = maxIdle;
		jedisPoolConfig.maxWait = maxWait;
		jedisPoolConfig.testOnBorrow = testOnBorrow;
		jedisPool = new JedisPool(jedisPoolConfig, ip, port, timeout);
		inited = true;
	}

	/**
	 * 初始化Jedis
	 */
	public static void initJedisConfig() {
		String ip = Props.getProperty("jedis.pool.config.ip", "127.0.0.1");
		String portStr = Props.getProperty("jedis.pool.config.port", "6379");
		String maxActiveStr = Props.getProperty("jedis.pool.config.maxActive", "8");
		String maxIdleStr = Props.getProperty("jedis.pool.config.maxIdle", "8");
		String maxWaitStr = Props.getProperty("jedis.pool.config.maxWait", "-1");
		String testOnBorrowStr = Props.getProperty("jedis.pool.config.testOnBorrow", "false");
		String timeoutStr = Props.getProperty("jedis.pool.config.timeout", "100000");
		initJedisConfig(ip, Integer.parseInt(portStr), Integer.parseInt(maxActiveStr), Integer.parseInt(maxIdleStr), Long.parseLong(maxWaitStr),
				Boolean.parseBoolean(testOnBorrowStr), Integer.parseInt(timeoutStr));
	}

}
